// system
#include <string.h>
#include <math.h>
#include <stdio.h>
// event
#include "eventDetection_module.h"
#include "event_int.h"
#include "lane_manager.h"

/**
*  @b Description
*  @n
*     事件记录函数
*  @param[in] handle
*		一个指向事件检测模块的指针
*  @param[in] tid
*		目标TID
*  @param[in] type
*      交通事件类型
*  @retval
*      None
*/
void recordEvent(void* handle, uint32_t tid, TrafficEventType type)
{
	DetectionModuleInstance* inst;
	inst = (DetectionModuleInstance*)handle;
	inst->result.traffic_Event[inst->result.cur_traffic_event_num].ID = tid;
	inst->result.traffic_Event[inst->result.cur_traffic_event_num].traffic_event = type;
	inst->result.cur_traffic_event_num++;
}

/**
*  @b Description
*  @n
*     判断一个目标是否为新目标
*  @param[in] handle
*		一个指向事件检测单元的指针
*  @retval
*      1：新目标，0：非新目标
*/
uint8_t ifNewTarget(void* handle)
{
	DetectionUnitInstance* inst;
	inst = (DetectionUnitInstance*)handle;
	if (inst->state == NotDetecting)
	{
		inst->state = Detecting;
		return 1;
	}
	return 0;
}
/**
 * 重置道路信息
 */
void resetTrafficJamLimits(DetectionModuleInstance* inst)
{
	for (int id = 0; id < inst->roadParam->count; id++)
	{
		switch (inst->param->parameRoad.moveDirection[id])
		{
		case MOVING_TOWARD:
			inst->result.traffic_Jam[id].head_pos = 10000;
			inst->result.traffic_Jam[id].tail_pos = 0;
			break;
		case MOVING_AWAY:
			inst->result.traffic_Jam[id].head_pos = 0;
			inst->result.traffic_Jam[id].tail_pos = 10000;
			break;
		}
	}
}
#pragma region 内部模块化处理函数
void  event_modulePreprocess(void* handle, GTRACK_targetDesc* t, uint16_t* tNum)
{
	//这块的逻辑和顺序需要重构，尤其是event_unitPrepross函数内对当前帧状态和数据的管理
	DetectionModuleInstance* inst;
	inst = (DetectionModuleInstance*)handle;
	inst->timestamp++;//临时当时间
	inst->result.date = inst->timestamp;

	resetTrafficJamLimits(inst);

	for (uint16_t num = 0; num < *tNum; num++)
	{
		uint16_t uid = t[num].uid;
		GTRACK_targetDesc* curTarget = &t[num];
		DetectionUnitInstance* uint = (DetectionUnitInstance*)inst->hTrack[uid];
		int isNewTargey = event_unitPrepross(uint, curTarget);//只传出是否是新目标这个信息，能否重构？
		curTarget->road_id = uint->cur_laneID;
		if (curTarget->state == TRACK_STATE_FREE)
		{
			if (uint->state == Detecting)//旧目标被释放才算驶离
			{
				recordEvent(inst, curTarget->tid, EVENT_DRIVE_AWAY);
				event_unitStop(inst->hTrack[uid]);
			}
		}
		else if(curTarget->state == TRACK_STATE_ACTIVE)
		{
			uint8_t curLane = uint->cur_laneID;
			
			if (curLane != 0)
			{
				if (isNewTargey)
				{
					uint->last_laneID = uint->cur_laneID;
					//printf("新增uid：%d,状态：%d \n", uid,((DetectionUnitInstance*)inst->hTrack[uid])->state);
					//如果是新加入的，则累积总车流量统计
					uint->state = Detecting; // 确认存活再给状态，防止带着TRACK_STATE_FREE来的，但是可以优化
					inst->result.traffic_FlowParameters[curLane - 1].lane_volume++;
					inst->result.total_volume++; //记录总车辆数量 
				}
				
				//正常检测出在车道 - 否则为无意义目标
				inst->result.traffic_Jam[curLane - 1].targetNum_of_lane++;//记录当前该车道车辆数量 索引为车道号
				inst->result.traffic_Jam[curLane - 1].lane_speed_sum += curTarget->S[3];//记录当前车道速度和 索引为车道号
				switch (inst->param->parameRoad.moveDirection[curLane-1])
				{
					case MOVING_TOWARD:
						if (curTarget->S[1] < inst->result.traffic_Jam[curLane-1].head_pos)
							inst->result.traffic_Jam[curLane - 1].head_pos = curTarget->S[1];
						if (curTarget->S[1] > inst->result.traffic_Jam[curLane - 1].tail_pos)
							inst->result.traffic_Jam[curLane - 1].tail_pos = curTarget->S[1];
						break;
					case MOVING_AWAY:
						if (curTarget->S[1] > inst->result.traffic_Jam[curLane - 1].head_pos)
							inst->result.traffic_Jam[curLane - 1].head_pos = curTarget->S[1];
						if (curTarget->S[1] < inst->result.traffic_Jam[curLane - 1].tail_pos)
							inst->result.traffic_Jam[curLane - 1].tail_pos = curTarget->S[1];
						break;
				}
			}	
		}
	}
}

void event_moduleLaneChangeDetection(void* handle, GTRACK_targetDesc* t, uint16_t* tNum)
{
	DetectionModuleInstance* moduleInstance;
	moduleInstance = (DetectionModuleInstance*)handle;
	for (uint16_t num = 0; num < *tNum; num++)
	{
		uint16_t uid = t[num].uid;
		GTRACK_targetDesc* curTarget = &t[num];
		if (curTarget->state == TRACK_STATE_ACTIVE)// 或者把判断放里面
		{
			DetectionUnitInstance* inst;
			inst = (DetectionUnitInstance*)(moduleInstance->hTrack[uid]);
			if (inst->cur_laneID != 0)
			{
				TrafficEventType curEventType = event_unitLaneChangeDetection(inst);
				if (curEventType != EVENT_NONE)
					recordEvent(moduleInstance, curTarget->tid, curEventType);
			}
		}
	}
}

void event_moduleRetrogradeDetection(void* handle, GTRACK_targetDesc* t, uint16_t* tNum) 
{
	DetectionModuleInstance* moduleInstance;
	moduleInstance = (DetectionModuleInstance*)handle;
	for (uint16_t num = 0; num < *tNum; num++)
	{
		uint16_t uid = t[num].uid;
		GTRACK_targetDesc* curTarget = &t[num];
		if (curTarget->state == TRACK_STATE_ACTIVE)// 或者把判断放里面
		{
			DetectionUnitInstance* inst;
			inst = (DetectionUnitInstance*)(moduleInstance->hTrack[uid]);
			if (inst->cur_laneID != 0)
			{
				TrafficEventType curEventType = event_unitRetrogradeDetection(inst);
				if (curEventType != EVENT_NONE)
					recordEvent(moduleInstance, curTarget->tid, curEventType);
			}
		}
	}
}

void event_moduleSpeedDetection(void* handle, GTRACK_targetDesc* t, uint16_t* tNum)//停止或逆行检测检测
{
	DetectionModuleInstance* moduleInstance;
	moduleInstance = (DetectionModuleInstance*)handle;
	for (uint16_t num = 0; num < *tNum; num++)
	{
		uint16_t uid = t[num].uid;
		GTRACK_targetDesc* curTarget = &t[num];
		if (curTarget->state == TRACK_STATE_ACTIVE)// 或者把判断放里面
		{
			DetectionUnitInstance* inst;
			inst = (DetectionUnitInstance*)(moduleInstance->hTrack[uid]);
			if (inst->cur_laneID != 0)
			{
				TrafficEventType curEventType = event_unitSpeedDetection(inst);
				if (curEventType != EVENT_NONE)
					recordEvent(moduleInstance, curTarget->tid, curEventType);
			}
		}
	}
}
#pragma endregion

#pragma region 交通流信息检测		
void event_moduleTrafficJamDetection(void* handle)
{
	DetectionModuleInstance* moduleInstance;
	moduleInstance = (DetectionModuleInstance*)handle;
	uint8_t l_lane;
	for (l_lane = 0; l_lane < moduleInstance->roadParam->count; l_lane++)
	{
		float cur_vel_sum = moduleInstance->result.traffic_Jam[l_lane].lane_speed_sum;
		uint8_t cur_veh_num = moduleInstance->result.traffic_Jam[l_lane ].targetNum_of_lane;
		float cur_avg_vel = cur_veh_num ? cur_vel_sum / cur_veh_num : 0;
		if (cur_veh_num >=2/*临时逻辑，车流数量不为0*/) //确保有车，否则无意义 但是逻辑需要细化
		{
			if (fabsf(cur_avg_vel) < moduleInstance->param->paramsThr.speed.traffic_jam_speed)
			{
				moduleInstance->result.traffic_Jam[l_lane].hasTrafficJam = 1;
			}
			moduleInstance->result.traffic_Jam[l_lane].queue_length = fabsf(moduleInstance->result.traffic_Jam[l_lane].head_pos - moduleInstance->result.traffic_Jam[l_lane].tail_pos);
			moduleInstance->result.traffic_FlowParameters[l_lane].avg_speed = fabsf(cur_avg_vel);//是否和trafficjam做一个合并，多此一举了
			moduleInstance->result.traffic_FlowParameters[l_lane].avg_space_headway = moduleInstance->result.traffic_Jam[l_lane].queue_length / cur_veh_num;
		}
	}
}

void event_moduleFlowDetection(void* handle, GTRACK_targetDesc* t, uint16_t* tNum)
{
	DetectionModuleInstance* moduleInstance;
	moduleInstance = (DetectionModuleInstance*)handle;
	uint8_t l_lane;
	uint32_t current_time = moduleInstance->timestamp; //这个值应该是当前时间
	for (int num = 0; num < *tNum; num++)//循环次数
	{
		uint16_t uid = t[num].uid;
		uint16_t tid = t[num].tid;
		GTRACK_targetDesc* curTarget = &t[num];
		if (curTarget->state == TRACK_STATE_ACTIVE)// 或者把判断放里面
		{
			DetectionUnitInstance* inst;
			inst = (DetectionUnitInstance*)(moduleInstance->hTrack[uid]);
			if (inst->cur_laneID == 0)
			{
				continue;
			}
			l_lane = inst->cur_laneID - 1;
			if ((curTarget->S[1] - moduleInstance->param->parameRoad.detection_line[l_lane])
				* (inst->last_y - moduleInstance->param->parameRoad.detection_line[l_lane]) < 0 && curTarget->S[1] != inst->last_y) //跨越断面
			{
				int l_last_Car_ID = moduleInstance->result.traffic_FlowParameters[l_lane].last_car_id;
				if (l_last_Car_ID != 0 && l_last_Car_ID != tid) //被记录过且不是同一辆车了 
				{
					int time_diff = current_time - moduleInstance->result.traffic_FlowParameters[l_lane].last_time;
					moduleInstance->result.traffic_FlowParameters[l_lane].time_headway = (float)time_diff;  //但是是不是要计算一下平均的
				}

				moduleInstance->result.traffic_FlowParameters[l_lane].last_car_id = tid;//更新上一次car的tid 累加唯一性（考虑数据大小，或者周期性清零）
				moduleInstance->result.traffic_FlowParameters[l_lane].last_time = current_time;
				//这里可以增加断面车流量统计
			}
			inst->last_y = curTarget->S[1];
		}
	}
}


void event_moduleTimeOccupancyDetection(void* handle, GTRACK_targetDesc* t, uint16_t* tNum)
{
	DetectionModuleInstance* moduleInstance;
	moduleInstance = (DetectionModuleInstance*)handle;
	uint8_t l_lane;
	uint32_t current_time = moduleInstance->timestamp; //这个值应该是当前时间
	for (l_lane = 0; l_lane < moduleInstance->roadParam->count ; l_lane++)
	{
		TimeOccupancyCounter* counter = &moduleInstance->result.traffic_FlowParameters[l_lane].time_occupancy_module;//车道号索引代表本车道
		DetectionZone* zone = &moduleInstance->param->parameRoad.zones[l_lane];

		bool lane_occupied = false;
		for (int num = 0; num < *tNum; num++)
		{
			uint16_t uid = t[num].uid;
			GTRACK_targetDesc* curTarget = &t[num];
			if (curTarget->state == TRACK_STATE_ACTIVE)// 或者把判断放里面
			{
				DetectionUnitInstance* inst;
				inst = (DetectionUnitInstance*)(moduleInstance->hTrack[uid]);
				if (inst->cur_laneID == l_lane + 1)
				{
					if (curTarget->S[1] >= zone->y_start && curTarget->S[1] <= zone->y_end)
					{
						lane_occupied = true;
						break; // 只要有一辆车在区域内即视为占用
					}
				}
			}
		}

		// 计算时间增量 
		float delta_time = (float)(current_time - counter->last_update);
		//状态变化处理
		if (lane_occupied != counter->current_state) 
		{
			// 状态切换时记录前一个状态的持续时间
			if (counter->current_state) 
			{ // 之前是占用状态
				counter->occupied_time += delta_time;
			}
			counter->current_state = lane_occupied;
			counter->last_update = current_time;
		}
		else 
		{
			// 状态未变化时持续累积
			if (counter->current_state) 
			{
				counter->occupied_time += delta_time;
			}
			counter->last_update = current_time;
		}

		//周期重置检查
		if ((current_time - counter->period_start) >= STAT_PERIOD_STAMP)
		{
			// 计算最终占有率（单位：百分比）
			float occupancy = (counter->occupied_time /(current_time - counter->period_start)) * 100.0f;
			moduleInstance->result.traffic_FlowParameters[l_lane].time_occupancy_rate = occupancy;
			// 重置计数器
			counter->occupied_time = 0.0f;
			counter->period_start = current_time;
		}
	}
}

void event_moduleSpaceOccupancyDetection(void* handle, GTRACK_targetDesc* t, uint16_t* tNum)
{
	DetectionModuleInstance* moduleInstance;
	moduleInstance = (DetectionModuleInstance*)handle;
	uint8_t l_lane;
	
	for (l_lane = 0; l_lane < moduleInstance->roadParam->count ; l_lane++)
	{
		DetectionZone* zone = &moduleInstance->param->parameRoad.zones[l_lane];

		const float zone_length = zone->y_end - zone->y_start;
		const float zone_width = moduleInstance->roadParam->lanes[l_lane].width; 

		// 计算网格数量
		const int cols = (int)(zone_length / GRID_SIZE) + 1;
		const int rows = (int)(zone_width / GRID_SIZE) + 1;

		//// 创建占用网格
		//bool* occupancy_grid = (bool*)gtrack_alloc(1,cols * rows * sizeof(bool)); // 这里可以提前分配
		//memset(occupancy_grid, 0, cols * rows * sizeof(bool));

		// 遍历所有车辆
		int vehicles_count = 0;
		for (int num = 0; num < *tNum; num++)
		{
			uint16_t uid = t[num].uid;
			GTRACK_targetDesc* curTarget = &t[num];
			if (curTarget->state == TRACK_STATE_ACTIVE)// 或者把判断放里面
			{
				DetectionUnitInstance* inst;
				inst = (DetectionUnitInstance*)(moduleInstance->hTrack[uid]);

				if (inst->cur_laneID == l_lane + 1)
				{
					if (curTarget->S[1] >= zone->y_start && curTarget->S[1] <= zone->y_end) //在检测区域内
					{
						// 车辆投影计算（先不考虑部分进入）
			/*			const float front = fmaxf(fminf(curTarget->S[1] + VEHICLE_LENGTH / 2, zone->y_end), zone->y_start);
						const float rear = fmaxf(fminf(curTarget->S[1] - VEHICLE_LENGTH / 2, zone->y_end), zone->y_start);*/
						//（先不考虑部分进入）
						const float front = curTarget->S[1] + VEHICLE_LENGTH ;
						const float rear = curTarget->S[1] - VEHICLE_LENGTH ;
						const float left = curTarget->S[0] - 2.5f / 2.f; // 2.5临时写的，更换为测出的车宽
						const float right = curTarget->S[0] + 2.5f / 2.f;

						// 转换为网格坐标
						const int start_col = (int)((rear - zone->y_start) / GRID_SIZE);
						const int end_col = (int)((front - zone->y_start) / GRID_SIZE);
					/*	const int start_row = (int)((left - zone->x_min) / GRID_SIZE);
						const int end_row = (int)((right - zone->x_min) / GRID_SIZE);*/
						const int start_row = (int)(0 / GRID_SIZE);
						const int end_row = (int)((right - left) / GRID_SIZE);

						// 标记占用
						//for (int c = start_col; c <= end_col; c++)
						//{
						//	for (int r = start_row; r <= end_row; r++)
						//	{
						//		if (c >= 0 && c < cols && r >= 0 && r < rows)
						//		{
						//			if (!occupancy_grid[c * rows + r])
						//			{
						//				occupancy_grid[c * rows + r] = true;//标记被计算过了
						//				vehicles_count++;
						//			}
						//		}
						//	}
						//}

						vehicles_count += (end_col - start_col) *(end_row - start_row); //等于占用这么多个格子
					}
				}
			}
		}
		// 计算占有率
		const float total_grids = (float)(cols * rows);
		const float occupied = vehicles_count * (GRID_SIZE * GRID_SIZE); 
		const float occupancy = occupied / ((zone_length * zone_width)) * 100.f;//输出百分比的数字部分
		moduleInstance->result.traffic_FlowParameters[l_lane].space_occupancy_rate = occupancy;
	}
}
#pragma endregion

void event_moduleReport(void* handle, Traffic_info* t)
{
	DetectionModuleInstance* inst;
	inst = (DetectionModuleInstance*)handle;
	if (t != NULL)
	{
		t->date = inst->result.date;
		t->cur_traffic_event_num = inst->result.cur_traffic_event_num;
		memcpy(t->traffic_Jam, inst->result.traffic_Jam, inst->roadParam->count* sizeof(Traffic_jam));
		memcpy(t->traffic_Event, inst->result.traffic_Event, t->cur_traffic_event_num* sizeof(Traffic_event));
		memcpy(t->traffic_FlowParameters, inst->result.traffic_FlowParameters, inst->roadParam->count * sizeof(Traffic_FlowParameters));
		t->total_volume = inst->result.total_volume;
		
		printf("累积车流：%d\n",t->total_volume);
		for (int id = 0; id < t->cur_traffic_event_num; id++)
		{
			printf("时间：%d - tid:%d - event:%d\n", t->date, t->traffic_Event[id].ID, t->traffic_Event[id].traffic_event);
		}

		for (int id = 0; id < inst->roadParam->count; id++)
		{
			int laneID = id + 1;
			if (inst->result.traffic_Jam[id].hasTrafficJam)
			{
				printf("车道: %d 发生拥堵 - 排队长度：%f，车头位置：%f ，车尾位置：%f \n", laneID, inst->result.traffic_Jam[id].queue_length,inst->result.traffic_Jam[id].head_pos, inst->result.traffic_Jam[id].tail_pos);
			}
		}
		for (int id = 0; id < inst->roadParam->count; id++)
		{
			int laneID = id + 1;
			uint16_t lane_volume = t->traffic_FlowParameters[id].lane_volume;
			float avg_speed = t->traffic_FlowParameters[id].avg_speed;
			float time_occupancy_rate = t->traffic_FlowParameters[id].time_occupancy_rate;
			float space_occupancy_rate = t->traffic_FlowParameters[id].space_occupancy_rate;
			float avg_time_headway = t->traffic_FlowParameters[id].time_headway;
			float avg_space_headway = t->traffic_FlowParameters[id].avg_space_headway;
			printf("车道：%d - 总流量：%d - 均速：%f - 时空占有率：%f/%f- 车头时距：%f - 平均车头空距：%f\n", laneID, lane_volume, avg_speed, time_occupancy_rate, space_occupancy_rate, avg_time_headway, avg_space_headway);
		}
	}
	memset(inst->result.traffic_Jam, 0, inst->roadParam->count * sizeof(Traffic_jam));//清空单帧车道信息统计
	inst->result.cur_traffic_event_num = 0;//清空当前事件总数 (清除索引）
}

#pragma region 外部接口定义
void event_Step(void* handle, GTRACK_targetDesc* t, uint16_t* tNum, Traffic_info* info)
{
	event_modulePreprocess(handle,t, tNum);// 预处理数据 - 定义大小车 + 统计流量 + 统计总流量 
	event_moduleLaneChangeDetection(handle, t, tNum); //变道事件检测
	event_moduleRetrogradeDetection(handle, t, tNum); //逆行事件检测
	event_moduleSpeedDetection(handle, t, tNum); //速度检测类型事件
	event_moduleFlowDetection(handle, t, tNum);//目前是计算断面车头时距，后面优化成交通流检测函数
	event_moduleTrafficJamDetection(handle); //输出单车道排队长度 + 车数 + 平均车速
	event_moduleTimeOccupancyDetection(handle ,t, tNum); //单车道时间占用率计算
	event_moduleSpaceOccupancyDetection(handle, t, tNum); //单车道空间占有率计算
	//todo 单车道 车头时距
	//todo 单车道 车头空距

	//疑问：友商有个检测点距离，可以输出平均车速 和 实时车速 
	//平均车速可以理解为当前检测帧在这个车道上的车的平均速度，也可以计算为某个周期时间内经过检测线的车的平均速度
	//实时车速如何定义？ 定义为当前经过检测线的车的速度 or 当前平均速度
	//同理 车道在线车辆间隔可以理解为当前帧单车道上车辆的平均间隔 
	//实时车道在线车辆间隔如何定义？
	event_moduleReport(handle, info);
}

void* event_creatEventModuleInstace(event_moduleConfig* config)
{
	DetectionModuleInstance* inst = NULL;
	inst = (DetectionModuleInstance*)gtrack_alloc(1, sizeof(DetectionModuleInstance));
	inst->maxNumTracks = config->maxNumTarget;
	inst->timestamp = 0;
	if (inst != NULL)
	{
		//创建道路参数
		event_creatRoad(inst, config);
	
		//给事件检测判断参数赋值
		inst->param = (EventConfiguration*)gtrack_alloc(1, sizeof(EventConfiguration));
		if (inst->param == NULL)
		{
			event_delete(inst);
			return NULL;
		}
		EventConfiguration* param = inst->param;
		param->major_version = config->thresholdParam.major_version;
		param->minor_version = config->thresholdParam.minor_version;
		
		uint16_t roadNum = config->laneParams.maxNumLanes;
		param->parameRoad.max_kph = (float*)gtrack_alloc(roadNum, sizeof(float));
		param->parameRoad.min_kph = (float*)gtrack_alloc(roadNum, sizeof(float));
		param->parameRoad.moveDirection = (laneDirection*)gtrack_alloc(roadNum, sizeof(laneDirection));
		param->parameRoad.type = (laneType*)gtrack_alloc(roadNum, sizeof(laneType));
		param->parameRoad.zones = (DetectionZone*)gtrack_alloc(roadNum, sizeof(DetectionZone));
		param->parameRoad.detection_line = (float*)gtrack_alloc(roadNum, sizeof(float));
		for (int idx = 0; idx < roadNum; idx++)
		{
			param->parameRoad.max_kph[idx] = config->laneParams.max_speed[idx];
			param->parameRoad.min_kph[idx] = config->laneParams.min_speed[idx];
			param->parameRoad.moveDirection[idx] = config->laneParams.moveDirection[idx];
			param->parameRoad.type[idx] = config->laneParams.type[idx];
			param->parameRoad.zones[idx] = config->laneParams.detectZone[idx];
			param->parameRoad.detection_line[idx] = config->laneParams.detection_line[idx];
		}

		param->paramsThr.speed.absolute_min_speed = config->thresholdParam.absolute_min_speed;
		param->paramsThr.speed.traffic_jam_speed = config->thresholdParam.traffic_jam_speed;
		param->paramsThr.speed.detect_Threshold = config->thresholdParam.speed;
		param->paramsThr.reversed_driving = config->thresholdParam.reversed_driving;
		param->paramsThr.lane_change = config->thresholdParam.lane_change;

		//提前分配事件计数数组
		Traffic_info* result = &inst->result;
		
		result->date = 0;
		result->total_volume = 0;
		result->cur_traffic_event_num = 0;
		//内存申请
		result->traffic_FlowParameters = (Traffic_FlowParameters*)gtrack_alloc(roadNum, sizeof(Traffic_FlowParameters));
		memset(result->traffic_FlowParameters, 0, roadNum * sizeof(Traffic_FlowParameters));
		result->traffic_Jam = (Traffic_jam*)gtrack_alloc(roadNum,sizeof(Traffic_jam));
		memset(result->traffic_Jam, 0, roadNum * sizeof(Traffic_jam));
		//初始化单独参数设定
		
		result->traffic_Event = (Traffic_event*)gtrack_alloc(inst->maxNumTracks, sizeof(Traffic_event));
		memset(result->traffic_Event, 0, inst->maxNumTracks *  sizeof(Traffic_event));
		result->cur_traffic_event_num = 0;
		
		//分配每个轨迹计数单元
		inst->hTrack = (void**)gtrack_alloc(inst->maxNumTracks, sizeof(DetectionUnitInstance*));
		for (uint8_t uid = 0; uid < inst->maxNumTracks; uid++)
		{
			inst->hTrack[uid] = event_unitCreate(inst->roadParam, inst->param); //预分配最大轨迹个事件检测历史数据块
		}
	}
	else
	{
		event_delete(inst);
		inst = NULL;
	}
	return inst;
}

void event_delete(void* handle)
{
	//删除这里没做完 应该有内存泄漏！2025.4.17
	if (handle)
	{
		DetectionModuleInstance*  inst = (DetectionModuleInstance*)handle;
		//释放inst->param
		if (inst->param)
		{
			//parameRoad指针释放
			if (inst->param->parameRoad.max_kph)
				gtrack_free(inst->param->parameRoad.max_kph, inst->roadParam->count*sizeof(float)); 
			if (inst->param->parameRoad.min_kph)
				gtrack_free(inst->param->parameRoad.min_kph, inst->roadParam->count * sizeof(float));
			if (inst->param->parameRoad.moveDirection)
				gtrack_free(inst->param->parameRoad.moveDirection, inst->roadParam->count * sizeof(laneDirection));
			if (inst->param->parameRoad.type)
				gtrack_free(inst->param->parameRoad.type, inst->roadParam->count * sizeof(laneType));
			if (inst->param->parameRoad.zones)
				gtrack_free(inst->param->parameRoad.zones, inst->roadParam->count * sizeof(DetectionZone));

			gtrack_free(inst->param, sizeof(EventConfiguration));
			inst->param = NULL;
		}
		//释放inst->roadParam
		if (inst->roadParam)
		{
			if (inst->roadParam->lanes->curve)
				gtrack_free(inst->roadParam->lanes->curve, inst->roadParam->capacity * sizeof(BezierCurve));
			if (inst->roadParam->lanes->y2x)
				gtrack_free(inst->roadParam->lanes->y2x, inst->roadParam->capacity * sizeof(float));
			gtrack_free(inst->roadParam, sizeof(inst->roadParam));
			inst->roadParam = NULL;
		}
			
		if (inst->hTrack)
		{
			for (int n = 0; n < inst->maxNumTracks; n++)
			{
				if (inst->hTrack[n] != NULL)
				{
					event_unitDelete(inst->hTrack[n]);
				}
			}
			gtrack_free(inst->hTrack, inst->maxNumTracks * sizeof(DetectionUnitInstance*));
			inst->hTrack = NULL;
		}
		gtrack_free(inst, sizeof(DetectionModuleInstance));
	}
}
#pragma endregion







